package edu.njust.httpmanager.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import edu.njust.httpmanager.annotation.AuthCheck;
import edu.njust.httpmanager.common.Result;
import edu.njust.httpmanager.constance.ResponseCode;
import edu.njust.httpmanager.constance.UserAuth;
import edu.njust.httpmanager.core.RequestHandler;
import edu.njust.httpmanager.entity.Api;
import edu.njust.httpmanager.entity.dto.ApiDto;
import edu.njust.httpmanager.service.IApiService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api")
public class ApiController {

    @Resource
    private IApiService apiService;

    @Resource
    private RequestHandler requestHandler;

    /**
     * 模拟发送请求
     */
    @PostMapping("/send")
    public Result<?> proxy(@RequestBody Api api) {

        if (api.getUrl() == null) {
            return Result.error(ResponseCode.PARAMS_ERROR);
        }

        return requestHandler.sendRequest(api);

    }

    @AuthCheck(UserAuth.EDITOR)
    @PutMapping("/{programId}")
    public Result update(@PathVariable Long programId, @RequestBody Api api) {

        apiService.updateById(api);

        return Result.success(apiService.getById(api.getId()));
    }

    @GetMapping("/{apiId}")
    public Result<Api> getByApiId(@PathVariable Long apiId) {
        Api api = apiService.getById(apiId);

        return Result.success(api);
    }

    @AuthCheck(UserAuth.EDITOR)
    @PostMapping("/{programId}")
    public Result save(@PathVariable Long programId, @RequestBody Api api) {

        if (api.getCatalogId() == null || api.getProgramId() == null) {
            return Result.error(ResponseCode.PARAMS_ERROR);
        }

        apiService.save(api);

        return Result.success(api);
    }

    @GetMapping("/list/{programId}")
    public Result<List<ApiDto>> findApi(@PathVariable(value = "programId") Long programId,
                                        @RequestParam(value = "searchKey", required = false) String searchKey,
                                        @RequestParam(value = "page") Integer page,
                                        @RequestParam("results") Integer results,
                                        @RequestParam(value = "sortOrder", required = false) String sortOrder) {
        // 分页对象用于封装
        Page<ApiDto> pageInfo = new Page<>(page, results);
        //在分页对象中封装返回data
        pageInfo.setRecords(apiService.getAllApi(programId, sortOrder, searchKey));

        return Result.success(pageInfo.getRecords());
    }

    @AuthCheck(UserAuth.EDITOR)
    @DeleteMapping("/{programId}")
    public Result deleteById(@PathVariable Long programId, Long apiId) {

        apiService.removeById(apiId);

        return Result.success();
    }
}
